package com.quad.innovators.salesease.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.quad.innovators.salesease.annotation.DataPermission;
import com.quad.innovators.salesease.annotation.FunctionPermission;
import com.quad.innovators.salesease.annotation.Log;
import com.quad.innovators.salesease.annotation.RepeatSubmit;
import com.quad.innovators.salesease.common.result.PageResultBean;
import com.quad.innovators.salesease.common.result.Result;
import com.quad.innovators.salesease.common.utils.ExcelUtils;
import com.quad.innovators.salesease.constants.SystemConstants;
import com.quad.innovators.salesease.enums.LogModuleEnum;
import com.quad.innovators.salesease.listener.SysUserImportListener;
import com.quad.innovators.salesease.model.common.Option;
import com.quad.innovators.salesease.model.dto.SysUserExportDTO;
import com.quad.innovators.salesease.model.dto.SysUserImportDTO;
import com.quad.innovators.salesease.model.form.SysUserForm;
import com.quad.innovators.salesease.model.query.SysUserPageQuery;
import com.quad.innovators.salesease.model.vo.SysUserInfoVO;
import com.quad.innovators.salesease.model.vo.SysUserPageVO;
import com.quad.innovators.salesease.model.vo.SysUserPasswordVO;
import com.quad.innovators.salesease.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Tag(name = "02.用户接口")
@RestController
@RequestMapping(SystemConstants.BACKEND_API + "/users")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService sysUserService;

    @Operation(summary = "用户分页列表")
    @GetMapping("/page")
    @Log(value = "用户分页列表", module = LogModuleEnum.USER)
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<PageResultBean<SysUserPageVO>> listPagedUsers(SysUserPageQuery queryParams) {
        PageResultBean<SysUserPageVO> result = sysUserService.listPagedUsers(queryParams);
        return Result.success(result);
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @FunctionPermission(permissionCode = "sys:user:add")
    @RepeatSubmit
    public Result<?> saveUser(@RequestBody @Valid SysUserForm userForm) {
        boolean result = sysUserService.saveUser(userForm);
        return Result.success(result);
    }

    @Operation(summary = "用户表单数据")
    @GetMapping("/{userCode}/form")
    @Parameters({
            @Parameter(name = "userCode", description = "用户ID"),
    })
    @FunctionPermission(permissionCode = "sys:user:detail")
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<SysUserForm> getUserForm(@PathVariable("userCode") String userCode) {
        SysUserForm formData = sysUserService.getUserFormData(userCode);
        return Result.success(formData);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/{userCode}")
    @FunctionPermission(permissionCode = "sys:user:edit")
    @Parameters({
            @Parameter(name = "userCode", description = "用户ID")
    })
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<?> updateUser(@PathVariable("userCode") String userCode, @RequestBody @Validated SysUserForm userForm) {
        boolean result = sysUserService.updateUser(userCode, userForm);
        return Result.success(result);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    @FunctionPermission(permissionCode = "sys:user:delete")
    @Parameters({
            @Parameter(name = "ids", description = "用户ID，多个以英文逗号(,)分割")
    })
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<Boolean> deleteUsers(@PathVariable String ids) {
        boolean result = sysUserService.deleteUsers(ids);
        return Result.success(result);
    }

    @Operation(summary = "修改用户状态")
    @PutMapping(value = "/{userCode}/status")
    @Parameters({
            @Parameter(name = "userCode", description = "用户ID"),
            @Parameter(name = "status", description = "用户状态(1:启用;0:禁用)")
    })
    @FunctionPermission(permissionCode = "sys:user:status")
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<Void> updateUserStatus(@PathVariable("userCode") String userCode, @RequestParam("status") Integer status) {
        boolean result = sysUserService.updateUserStatus(userCode, status);
        return Result.judge(result);
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/me")
    public Result<SysUserInfoVO> getCurrentUserInfo() {
        SysUserInfoVO userInfoVO = sysUserService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }


    @Operation(summary = "获取用户的密码信息")
    @GetMapping("/{userCode}/password")
    @FunctionPermission(permissionCode = "sys:user:view-password")
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<SysUserPasswordVO> getUserPassword(@PathVariable("userCode") String userCode) {
        SysUserPasswordVO sysUserPasswordVO = sysUserService.getUserPassword(userCode);
        return Result.success(sysUserPasswordVO);
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/import/template")
    @FunctionPermission(permissionCode = "sys:user:import")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        excelWriter.finish();
    }

    @Operation(summary = "导入用户")
    @PostMapping("/import")
    @FunctionPermission(permissionCode = "sys:user:import")
    public Result<String> importUsers(  @Parameter(
            name = "file",
            description = "表单文件对象",
            required = true,
            in = ParameterIn.DEFAULT,
            schema = @Schema(name = "file", format = "binary")
    ) @RequestPart(value = "file")MultipartFile file) throws IOException {
        SysUserImportListener listener = new SysUserImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), SysUserImportDTO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出用户")
    @GetMapping("/export")
    @FunctionPermission(permissionCode = "sys:user:export")
    @DataPermission(permissionCode = "sys:user:data-permission")
    public void exportUsers(SysUserPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "用户列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysUserExportDTO> exportUserList = sysUserService.listExportUsers(queryParams);
        EasyExcel.write(response.getOutputStream(), SysUserExportDTO.class).sheet("用户列表")
                .doWrite(exportUserList);
    }



    @Operation(summary = "重置用户密码")
    @PutMapping(value = "/{userCode}/password/reset")
    @FunctionPermission(permissionCode = "sys:user:update-password")
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<?> resetPassword(@PathVariable String userCode, @RequestParam String password) {
        boolean result = sysUserService.resetPassword(userCode, password);
        return Result.judge(result);
    }

    @Operation(summary = "用户下拉列表")
    @GetMapping("/options")
    @DataPermission(permissionCode = "sys:user:data-permission")
    public Result<List<Option<String>>> listUserOptions() {
        List<Option<String>> list = sysUserService.listRoleOptions();
        return Result.success(list);
    }
}
